#!/usr/bin/python
import subprocess,os,re,datetime,sys,linecache,codecs,chardet,time


# 执行batch脚本
def run_batch(filename):
    os.system(filename)

# 执行cmd命令
def exec_cmd(cmd):
    # cmd = 'cmd.exe d:/start.bat'
    p = subprocess.Popen("cmd.exe /c" + cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    curline = p.stdout.readline()
    while (curline != b''):
        print(curline)
        curline = p.stdout.readline()
    p.wait()
    if p.returncode != 0: #执行失败
        print ("exec cmd error: "+cmd+"\n")
        return False

# 清空文件
def clear_file(filename):
    f = open(filename, 'w')
    f.truncate()
    f.close()

# 读取文件内容
def readfile(filename):
    f = open(filename, 'r')
    content = f.read()
    f.close()
    return content

# 读取字符
def read_char(filename):
    f = open(filename, 'rb')
    content = f.read()
    f.close()
    return content

# 覆盖写入文件内容
def writefile(filename,content):
    f = open(filename, 'w')
    f.write(content)
    f.close()

# 追加写入文件内容
def appendfile(filename,content):
    f = open(filename, 'a')
    f.write(content)
    f.close()

# 读取指定行数据
def read_line_num(filename,num):
    f = open(filename, 'r')
    content = f.readlines()
    f.close()
    return content[num]

# 获取文件行数
def get_line_num(filename):
    f = open(filename, 'r')
    content = f.readlines()
    f.close()
    return len(content)

# 截取字符串
def split_line(filename,num):
    f = open(filename, 'r')
    content = f.readline()
    f.close()
    content = content.split(num)
    return content

# 替换文本内容
def replace(filename,old_str,new_str):
    f = open(filename, 'r')
    content = f.read()
    f.close()
    content = content.replace(old_str,new_str)
    f = open(filename, 'w')
    f.write(content)
    f.close()

# 创建目录
def mkdir(path):
    path=path.strip()
    path=path.rstrip("\\")
    isExists=os.path.exists(path) #查询目录是否存在
    if not isExists:
        os.makedirs(path) 
        print (path+' 创建成功')
        return True
    else:
        print (path+' 目录已存在')
        return False

# 删除目录
def del_dir(path):
    if os.path.isdir(path):
        for i in os.listdir(path):
            path_file = os.path.join(path,i)
            if os.path.isfile(path_file):
                os.remove(path_file)
            else:
                del_dir(path_file)
        os.rmdir(path)

# 等待毫秒
def wait_ms(ms):
    time.sleep(ms/1000.0)

# 查找国家
def find_country(filename):
    content = read_line_num(filename,0) # 读取文本指定字符串
    print(content)
    writefile(temp_file,content) # 写入临时文件
    replace(temp_file,'\n','')  # 替换文本指定字符串
    content = split_line(temp_file,' ') # 截取字符串
    clear_file(temp_country_file) # 清空文件
    writefile(temp_country_file,content[2]) # 写入文件
    content = readfile(temp_country_file) # 读取文件内容
    clear_file(temp_country_file) # 清空文件
    for item in content:
        appendfile(temp_country_file,item + ' ') # 追加写入文件
    os.remove(temp_file) # 删除文件

# 查找信道
def find_channel(filename):
    clear_file(temp_channel_file) # 清空文件
    for i in {1,2}:
        content = read_line_num(filename,i) # 读取文本指定字符串
        print(content)
        writefile(temp_file,content) # 写入临时文件
        replace(temp_file,'\n','')  # 替换文本指定字符串
        content = split_line(temp_file,' ') # 截取字符串
        content = content[2:] # 去除前2个值
        num = len(content) # 获取文件行数
        # 打印文件内容
        for i in range(num):
            appendfile(temp_channel_file,content[i] + '\n') # 追加写入文件
    os.remove(temp_file) # 删除文件

# 截取国家和信道
def find_country_channel(filename):
    del_blank_line(filename) # 删除空行
    find_country(filename) # 查找国家
    find_channel(filename) # 查找信道

# 替换内容
def replace_content(old_filename,new_filename,channel_num):
    content = readfile(old_filename) # 读取文件内容
    writefile(new_filename,content) # 写入临时文件
    content = readfile(temp_country_file) # 读取文件内容
    replace(new_filename,'{0, 0}','{\''+ content[0] + '\', \'' + content[2] + '\'}') # 替换国家
    replace(new_filename, ', 36', ', ' + str(channel_num)) #替换信道
    content = readfile(new_filename)
    appendfile(des_struct_file, content + '\n')

# 删除空行
def del_blank_line(filename):
    f = open(filename, 'r')
    content = f.readlines()
    f.close()
    f = open(filename, 'w')
    for i in content:
        if i.strip():
            f.write(i)
    f.close()

# 获取国家配置(FCC/CE)
def get_country_content(certification_standards):
    if certification_standards == 'FCC':
        country_filename=path+'\\'+'FCC_CE_Country'+'\\'+'FCC.txt'
        src_struct_2G4=path+'\\'+'Code'+'\\'+ 'FCC_2G4_Code.txt'
        src_struct_5GBAND1=path+'\\'+'Code'+'\\'+ 'FCC_5GBAND1_Code.txt'
        src_struct_5GBAND2=path+'\\'+'Code'+'\\'+ 'FCC_5GBAND2_Code.txt'
        src_struct_5GBAND3=path+'\\'+'Code'+'\\'+ 'FCC_5GBAND3_Code.txt'
        src_struct_5GBAND4=path+'\\'+'Code'+'\\'+ 'FCC_5GBAND4_Code.txt'
    elif certification_standards == 'CE':
        country_filename=path+'\\'+'FCC_CE_Country'+'\\'+'CE.txt'
        src_struct_2G4=path+'\\'+'Code'+'\\'+ 'CE_2G4_Code.txt'
        src_struct_5GBAND1=path+'\\'+'Code'+'\\'+ 'CE_5GBAND1_Code.txt'
        src_struct_5GBAND2=path+'\\'+'Code'+'\\'+ 'CE_5GBAND2_Code.txt'
        src_struct_5GBAND3=path+'\\'+'Code'+'\\'+ 'CE_5GBAND3_Code.txt'
        src_struct_5GBAND4=path+'\\'+'Code'+'\\'+ 'CE_5GBAND4_Code.txt'
    num = get_line_num(country_filename) # 获取文件行数
    clear_file(temp_adb_get_file) # 清空文件
    for i in range(num):
        str_country = read_line_num(country_filename, i)
        writefile(temp_adb_get_file,'country is ' + str_country + '\n') # 写入文件
        exec_cmd('adb shell cmd wifi force-country-code enabled ' + str_country) # 执行命令
        exec_cmd('adb shell wpa_cli -iwlan0 get_capability channels >> ' + temp_adb_get_file) # 执行命令
        exec_cmd('adb shell cmd wifi force-country-code disabled') # 执行命令
        # 保留所有adb数据
        content = readfile(temp_adb_get_file)
        appendfile(temp_all_file, content)
        del_blank_line(temp_all_file) # 删除空行
        # 配置文件
        find_country_channel(temp_adb_get_file) # 查找国家和信道
        line_num = get_line_num(temp_channel_file) # 获取文件行数
        for num in range(line_num):
            channel_str = read_line_num(temp_channel_file, num) # 读取信道
            channel = int(channel_str.strip('\n'))  # 转换为整数
            # 替换内容
            if channel < 36:
                replace_content(src_struct_2G4,temp_content_file,channel)
            elif channel >= 36 and channel <= 48:
                replace_content(src_struct_5GBAND1,temp_content_file,channel)
            elif channel >= 52 and channel <= 64:
                replace_content(src_struct_5GBAND2,temp_content_file,channel)
            elif channel >= 100 and channel <= 144:
                replace_content(src_struct_5GBAND3,temp_content_file,channel)
            elif channel >= 149 and channel <= 165:
                replace_content(src_struct_5GBAND4,temp_content_file,channel)


if __name__ == '__main__':
    path = os.getcwd()  # 获取当前路径

    # 日志文件
    mkdir(path+'\\'+'temp') # 创建日志目录
    temp_country_file=path+'\\'+'temp'+'\\'+'.temp_country.txt' # 临时国家信息
    temp_channel_file=path+'\\'+'temp'+'\\'+'.temp_channel.txt' # 临时信道信息
    temp_adb_get_file=path+'\\'+'temp'+'\\'+'.temp_adb_get.txt' # 临时adb信息
    temp_content_file=path+'\\'+'temp'+'\\'+'.temp_content.txt' # 临时文本信息
    temp_all_file=path+'\\'+'temp'+'\\'+'.temp_all.txt'         # 保留adb信息
    temp_file=path+'\\'+'temp'+'\\'+'.temp.txt'                 # 临时配置文件
    # 配置文件
    des_struct_file=path+'\\'+ 'des_struct.txt'                 # 最终配置文件

    # 获取配置
    clear_file(des_struct_file)
    clear_file(temp_all_file)
    get_country_content('FCC') # 获取FCC国家配置
    get_country_content('CE') # 获取CE国家配置

    del_dir(path+'\\'+'temp') # 删除日志目录